#include "circle_buffer.hpp"

namespace mina
{
	IMPL_LOGGER(CircleBuffer, logger);

	CircleBuffer::CircleBuffer(int block_size, int block_num)
		: _block_size(block_size),
		_circle_buffer(block_num)
	{
		_block_size    = block_size;

		_base          = new char[block_size * block_num];
		_end           = _base + block_size * block_num;

		assert(NULL != _base);

		char * addr    = NULL;

		for (int i = 0; i < (block_num - 1); ++ i)
		{
			addr       = _base + i * block_size;
			assert(0 == _circle_buffer.push(addr));
		}
		// @TODO
	}

	CircleBuffer::~CircleBuffer()
	{
		SAFE_DELETE_ARR(_base);
	}

	char * CircleBuffer::allocate()
	{
		if (empty())
		{
			return NULL;
		}

		char * addr = NULL;

		assert(0 == _circle_buffer.front(addr));
		_circle_buffer.pop();

		return addr;
	}

	void CircleBuffer::deallocate(void * addr)
	{
		assert(addr >= _base && addr < _end);

		assert(0 == _circle_buffer.push((char*)addr));
	}
}

